package com.windx.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.solon.service.impl.ServiceImpl;
import com.windx.exception.ApiAsserts;
import com.windx.exception.ApiException;
import com.windx.mapper.BmsFollowMapper;
import com.windx.mapper.BmsTopicMapper;
import com.windx.mapper.UmsUserMapper;
import com.windx.model.dto.LoginDTO;
import com.windx.model.dto.RegisterDTO;
import com.windx.model.entity.BmsFollow;
import com.windx.model.entity.BmsPost;
import com.windx.model.entity.UmsUser;
import com.windx.model.vo.ProfileVO;
import com.windx.service.IUmsUserService;
import com.windx.utils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.solon.annotation.Db;
import org.noear.solon.aspect.annotation.Service;
import org.noear.solon.data.annotation.Tran;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;


@Slf4j
@Service
public class IUmsUserServiceImpl extends ServiceImpl<UmsUserMapper, UmsUser> implements IUmsUserService {

    @Db
    private UmsUserMapper umsUserMapper;
    @Db
    private BmsTopicMapper bmsTopicMapper;
    @Db
    private BmsFollowMapper bmsFollowMapper;

    @Tran
    @Override
    public UmsUser executeRegister(RegisterDTO dto) {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<UmsUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UmsUser::getUsername, dto.getName()).or().eq(UmsUser::getEmail, dto.getEmail());
        UmsUser umsUser = umsUserMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(umsUser)) {
            ApiAsserts.fail("账号或邮箱已存在！");
        }
        UmsUser addUser = UmsUser.builder()
                .username(dto.getName())
                .alias(dto.getName())
                .password(MD5Util.getPwd(dto.getPass()))
                .email(dto.getEmail())
                .createTime(new Date())
                .status(true)
                .build();
        umsUserMapper.insert(addUser);

        return addUser;
    }

    @Tran
    @Override
    public UmsUser getUserByUsername(String username) {
        return umsUserMapper.selectOne(new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getUsername, username));
    }

    @Tran
    @Override
    public String executeLogin(LoginDTO dto) {
        String token = null;
        try {
            UmsUser user = getUserByUsername(dto.getUsername());
            String encodePwd = MD5Util.getPwd(dto.getPassword());
            if (!encodePwd.equals(user.getPassword())) {
                throw new ApiException("密码错误");
            }
            StpUtil.login(user.getUsername());
            token = StpUtil.getTokenValue();
        } catch (Exception e) {
            log.warn("用户不存在or密码验证失败=======>{}", dto.getUsername());
        }
        return token;
    }

    @Tran
    @Override
    public ProfileVO getUserProfile(String id) {
        ProfileVO profile = new ProfileVO();
        UmsUser user = umsUserMapper.selectById(id);
        try {
            BeanUtils.copyProperties(profile, user);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        // 用户文章数
        Long count = bmsTopicMapper.selectCount(new LambdaQueryWrapper<BmsPost>().eq(BmsPost::getUserId, id));
        profile.setTopicCount(Math.toIntExact(count));

        // 粉丝数
        Long followers = bmsFollowMapper.selectCount(new LambdaQueryWrapper<BmsFollow>().eq(BmsFollow::getParentId, id));
        profile.setFollowerCount(Math.toIntExact(followers));

        return profile;
    }
}
